import { useAppDataDoneModel } from '@/models/useGlobalModel';
import { useUserModel } from '@/models/useUserModel';
import type { DependencyList, EffectCallback } from 'react';
import { useEffect, useRef } from 'react';
import { useRecoilValue } from 'recoil';

/**
 * app加载完成并且用户信息已经获取
 */
export default (
  /**
   * 要执行的effect
   */
  effect: EffectCallback,
  /**
   * 需要监听的deps
   */
  deps: DependencyList,
  /**
   * 结束销毁的方法
   */
  unEffect?: () => void,
  /**
   * 监听用户切换，开启后用户更新，就会执行一次
   * @default false
   */
  isOnChange: boolean = false,
): void => {
  const appDataDoneModel = useRecoilValue(useAppDataDoneModel);
  const userModel = useRecoilValue(useUserModel);
  const doneRef = useRef<boolean>(false);

  useEffect(() => {
    if (appDataDoneModel && userModel) {
      if (isOnChange) {
        effect();
      } else {
        if (!doneRef.current) {
          effect();
          doneRef.current = true;
        }
      }
    }

    return () => {
      if (unEffect) {
        unEffect();
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [...deps, appDataDoneModel, userModel]);
};
